package liaotian;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;
import java.util.List;

public class ClientHandler implements Runnable {

    private Socket clientSocket;
    private List<PrintWriter> clientWriters;

    public ClientHandler(Socket clientSocket, List<PrintWriter> clientWriters) {
        this.clientSocket = clientSocket;
        this.clientWriters = clientWriters;
    }

    @Override
    public void run() {
        try {
            BufferedReader in = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
            String nickname = in.readLine();
            System.out.println("User '" + nickname + "' has joined the chat.");

            String message;
            while ((message = in.readLine()) != null) {
                System.out.println("Received message: " + message);
                // 检查是否为私聊消息
                if (message.startsWith("/msg ")) {
                    String[] parts = message.split(" ", 3);
                    String targetUser = parts[1];
                    String privateMessage = nickname + " (private): " + parts[2];
                    sendPrivateMessage(targetUser, privateMessage);
                } else {
                    // 将客户端发送的消息广播给其他客户端
                    for (PrintWriter writer : clientWriters) {
                        writer.println(nickname + ": " + message);
                    }
                }
            }

            // 客户端断开连接，从列表中移除
            clientWriters.remove(new PrintWriter(clientSocket.getOutputStream(), true));
            System.out.println("User '" + nickname + "' has left the chat.");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    private void sendPrivateMessage(String targetUser, String message) {
        for (PrintWriter writer : clientWriters) {
            if (writer != null ) {
                writer.println(message);
            }
        }
    }
}
